package com.andersen.web.controller;


import com.andersen.database.entity.ComponentTypeEntity;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Avseenko Dmitrij
 * Date: 25.02.14
 * Time: 12:19
 * To change this template use File | Settings | File Templates.
 */

@Controller
public class EditComponentsController extends AbstractController{


    @RequestMapping(value = "/editComponents")
    public String openEditComponentsPagePOST (HttpServletRequest req, HttpServletResponse response){
        return "editComponents";
    }

    @RequestMapping(value = "/editComponents", method = RequestMethod.GET)
    public String openEditComponentsPageGET (ModelMap map) {
        return "editComponents";
    }


    // Получение списка типов компонентов.
    @RequestMapping(value = "/getTypes", method = RequestMethod.POST)
    public @ResponseBody JSONObject getUserList(HttpServletRequest req, HttpServletResponse response) throws IOException {

        // при построении выпадающего списка он должен быть первым (родительский id)
        // если пришло -1 то перемещение не нужно
        Integer parentId = Integer.parseInt(req.getParameter("parentId"));

        ArrayList<ComponentTypeEntity> listComponentType = new ArrayList<ComponentTypeEntity>(componentTypeService.getComponentsType());

        if(parentId != -1){

            int index;
            for (ComponentTypeEntity entity : listComponentType){
                if(entity.getId() == parentId){
                    index = listComponentType.indexOf(entity);

                    ComponentTypeEntity entityBuf;

                    entityBuf = listComponentType.get(0);
                    listComponentType.set(0,entity);
                    listComponentType.set(index,entityBuf);
                    break;
                }
            }
        }

        JSONArray arrayJson = new JSONArray();

        for (ComponentTypeEntity entity : listComponentType){

            JSONObject jsonObject = new JSONObject();

            jsonObject.accumulate("id",entity.getId());
            jsonObject.accumulate("name",entity.getName());
            jsonObject.accumulate("parent_type_id",entity.getParentTypeId());

            arrayJson.add(jsonObject);
        }

        JSONObject retObj = new JSONObject();
        retObj.accumulate("values",arrayJson);

        return retObj;
    }

    // Получение списка подтипов компонентов.
    @RequestMapping(value = "/getSubType", method = RequestMethod.POST)
    public @ResponseBody JSONObject getUserList(@ModelAttribute("idCurrentTypeFormat") long idCurrentType, HttpServletRequest req, HttpServletResponse response) throws IOException {

        List<ComponentTypeEntity> listSubCategory = componentTypeService.getCompotetnsSubTypeForId(idCurrentType);

        JSONArray arrayJson = new JSONArray();

        for (ComponentTypeEntity entity : listSubCategory){

            JSONObject jsonObject = new JSONObject();

            jsonObject.accumulate("id",entity.getId());
            jsonObject.accumulate("name",entity.getName());
            jsonObject.accumulate("parent_type_id",entity.getParentTypeId());

            arrayJson.add(jsonObject);
        }

        JSONObject ret = new JSONObject();
        ret.accumulate("aaData",arrayJson);
        long tableSize = listSubCategory.size();
        ret.accumulate("iTotalRecords", String.valueOf(tableSize));
        ret.accumulate("iTotalDisplayRecords", String.valueOf(tableSize));

        return ret;
    }


    // Добавление типа компонентов.
    @RequestMapping(value = "/addType", method = RequestMethod.POST)
    public void addType(HttpServletRequest req, HttpServletResponse response) throws IOException{

        String newType = req.getParameter("newType");
        componentTypeService.addNewComponentType(newType);
    }

    //Добавление подтипа компонентов.
    @RequestMapping(value = "/addSubType", method = RequestMethod.POST)
    public void addSubType(HttpServletRequest req, HttpServletResponse response) throws IOException{

        String newSubType = req.getParameter("newSubType");
        Integer parentId = Integer.parseInt(req.getParameter("parentId"));
        componentTypeService.addNewComponentSubType(newSubType,parentId);
    }


    // Редактирование типа компонетов.
    @RequestMapping(value = "/editType", method = RequestMethod.POST)
    public void editType(HttpServletRequest req, HttpServletResponse response) throws IOException{

        Integer idType = Integer.parseInt(req.getParameter("idType"));
        String nameType = req.getParameter("newType");
        componentTypeService.editComponentType(idType,nameType);
    }

    // Редактирование подтипа компонетов.
    @RequestMapping(value = "/editSubType", method = RequestMethod.POST)
    public void editSubType(HttpServletRequest req, HttpServletResponse response) throws IOException{

        Integer idSubType = Integer.parseInt(req.getParameter("idSubType"));
        String nameSubType = req.getParameter("newSubType");
        Integer parentSubType = Integer.parseInt(req.getParameter("newParent"));
        componentTypeService.editComponentSubType(idSubType,nameSubType,parentSubType);
    }


    // Есть ли наследники у типа компонентов.
    @RequestMapping(value = "/getHeirTypes", method = RequestMethod.POST)
    public @ResponseBody JSONObject getHeirTypes(HttpServletRequest req, HttpServletResponse response) throws IOException{

        Integer idType = Integer.parseInt(req.getParameter("parentId"));
        int count = componentTypeService.getNumberOfHeirsType(idType);

        JSONObject retObj = new JSONObject();
        retObj.accumulate("heir",count);

        return retObj;
    }

    // Есть ли наследники у подтипа компонентов.
    @RequestMapping(value = "/getHeirSubTypes", method = RequestMethod.POST)
    public @ResponseBody JSONObject getHeirSubTypes(HttpServletRequest req, HttpServletResponse response) throws IOException{

        Integer idType = Integer.parseInt(req.getParameter("parentId"));
        int count = componentTypeService.getNumberOfHeirsSubType(idType);

        JSONObject retObj = new JSONObject();
        retObj.accumulate("heir",count);

        return retObj;
    }


    // Удаление типа\подтипа компонетов.
    @RequestMapping(value = "/removeType", method = RequestMethod.POST)
    public void removeType(HttpServletRequest req, HttpServletResponse response) throws IOException{

        Integer idType = Integer.parseInt(req.getParameter("idType"));
        componentTypeService.removeComponentType(idType);
    }

}
